﻿using Generico.Coneccion;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace RosarioFinanzas.Sorteo
{
    public partial class Sorteo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
      
            var cn = new ClsConeccion();
            cn.Abrir();
            var rd = cn.EjecutarSpDataReader("sp_GetSorteo");
            int nro=0;
            while (rd.Read())
            {
                nro=Convert.ToInt32(rd["idSorteo"]);
                this.Session.Add("IdSorteo", nro);
                this.Session.Add("Sorteo", rd["Sorteo"].ToString());
                this.Session.Add("FechaSorteo", rd["FechaSorteo"].ToString());
                //txtId.Text = .ToString();
                //this.txtSorteo.Text = rd["Sorteo"].ToString();
                lblSorteo.Text = rd["Descripcion1"].ToString();
                lblSorteo2.Text = rd["Descripcion2"].ToString();
                this.lblDesc3.Text = rd["Descripcion3"].ToString();
                this.lblParticipantes.Text = rd["participantes"].ToString();
                //this.txtFechaSorteo.Text = rd["FechaSorteo"].ToString();
                //this.txtVigencia.Text = rd["Vigencia"].ToString();


                //Add Meta Tag
                HtmlMeta title = new HtmlMeta();
                title.HttpEquiv = "title";
                title.Name = "title";
                title.Content = rd["TituloMetaEtiqueta"].ToString();
                this.Page.Header.Controls.Add(title);

                //Add Description Meta Tag
                HtmlMeta description = new HtmlMeta();
                description.HttpEquiv = "description";
                description.Name = "description";
                description.Content = "Sorteo de Rosario Finanzas";
                this.Page.Header.Controls.Add(description);

                // Social Media Tags
                HtmlMeta tagOgTitle = new HtmlMeta();
                tagOgTitle.Attributes.Add("property", "og:title");
                tagOgTitle.Content = rd["TituloMetaEtiqueta"].ToString();
                Page.Header.Controls.Add(tagOgTitle);

                HtmlMeta tagOgDescription = new HtmlMeta();
                tagOgDescription.Attributes.Add("property", "og:description");
                tagOgDescription.Content = "Sorteo de Rosario Finanzas";
                Page.Header.Controls.Add(tagOgDescription);

                HtmlMeta tagOgImage = new HtmlMeta();
                tagOgImage.Attributes.Add("property", "og:image");
                tagOgImage.Content = "http://rosariofinanzas.com.ar/Imagenes/FB_Posts.jpg";
                Page.Header.Controls.Add(tagOgImage);

                HtmlMeta tagOgUrl = new HtmlMeta();
                tagOgUrl.Attributes.Add("property", "og:url");
                tagOgUrl.Content = "http://rosariofinanzas.com.ar/Sorteo/Sorteo.aspx?nro=" + nro.ToString();
                Page.Header.Controls.Add(tagOgUrl);
                
            }
            rd.Close();         
                  
             
        

            cn.Cerrar();
        }
        [WebMethod]
        public static string strFecha(string str)
        {

            string[] dayarray = { "Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado" };
            string[] montharray = { "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };
            var daym = DateTime.Today.Day.ToString();
            var year = DateTime.Today.Year.ToString();
            var day = Convert.ToInt32(DateTime.Today.DayOfWeek);
            var month = DateTime.Today.Month - 1;
            return dayarray[day] + ", " + daym + " de " + montharray[month] + " del " + year + " ";

        }
              

        protected void btnEnviar_Click(object sender, EventArgs e)
        {
            var cn = new ClsConeccion();
            cn.Abrir();
            cn.AgregarParametros("Nombre", this.txtNombre.Text);
            cn.AgregarParametros("Apellido", this.txtApellido.Text);
            cn.AgregarParametros("Provincia", this.txtProvincia.Text);
            cn.AgregarParametros("Mail", this.txtEmail.Text.ToLower());
            cn.AgregarParametros("TipoIngreso", 1);
            cn.AgregarParametros("IdSorteo", Convert.ToInt32(this.Session["IdSorteo"]));
            cn.AgregarParametros("DNI", this.txtDNI.Text);

            var rd = cn.EjecutarSpDataReader("sp_GrabarParticipante");
            while (rd.Read())
            {

                if (rd["nro"].ToString() == "-1")
                {
                    txtNombre.Enabled = false;
                    txtApellido.Enabled = false;
                    txtDNI.Enabled = false;
                    txtProvincia.Enabled = false;
                    txtEmail.Enabled = false;
                    btnEnviar.Enabled = false;
                    lblUsuarioInscripto.Text = "Usted ya se encuentra participando en este sorteo. Obtenga más chances compartiendo el sorteo en las redes sociales.";
                }
                else
                {

                    var correo = new System.Net.Mail.MailMessage
                    {
                        From = new System.Net.Mail.MailAddress("info@rosariofinanzas.com.ar")
                    };
                    correo.To.Add(this.txtEmail.Text);
                    correo.Subject = "Sorteo Rosario Finanzas - " + this.Session["Sorteo"].ToString();

                    string Body = GetHtmlEmailSorteo(this.Session["Sorteo"].ToString(), Convert.ToDateTime(this.Session["FechaSorteo"]).ToShortDateString(), rd["nro"].ToString());

                    List<string> list = new List<string>();

                    int c = 1;
                    while (Body.IndexOf("<img alt=\"\" src=\"http") > 0)
                    {
                        string aux = Body.Substring(Body.IndexOf("<img alt=\"\" src=\"http") + 17);
                        string aux2 = Body.Substring(Body.IndexOf("<img alt=\"\" src=\"http") + 17, aux.IndexOf("\" />"));
                        if (aux2.IndexOf("style") > 0)
                            aux2 = aux2.Substring(0, aux2.IndexOf("style") - 2);
                        list.Add(aux2);
                        Body = Body.Replace(aux2, "cid:Imagen" + c.ToString());
                        c++;
                    }

                    AlternateView htmlView =
                        AlternateView.CreateAlternateViewFromString(Body,
                                                Encoding.UTF8,
                                                MediaTypeNames.Text.Html);

                    c = 1;
                    foreach (string link in list)
                    {
                        LinkedResource img = null;
                        if (LinkExtension(link) == "Gif")
                            img = new LinkedResource(Link(link), MediaTypeNames.Image.Gif);
                        if (LinkExtension(link) == "jpg")
                            img = new LinkedResource(Link(link), MediaTypeNames.Image.Jpeg);
                        if (LinkExtension(link) != "jpg" && LinkExtension(link) != "Gif")
                            img = new LinkedResource(Link(link), "image/png");
                        img.ContentId = "Imagen" + c.ToString();
                        htmlView.LinkedResources.Add(img);
                        c++;
                    }

                    correo.AlternateViews.Add(htmlView);

                    correo.Priority = System.Net.Mail.MailPriority.Normal;

                    //var smtp = new System.Net.Mail.SmtpClient
                    //{
                    //    Host = "mail.rosariofinanzas.com.ar",
                    //    Credentials =
                    //        new System.Net.NetworkCredential("info@rosariofinanzas.com.ar", "Info123456")
                    //};

                    //var smtp = new System.Net.Mail.SmtpClient
                    //{
                    //    EnableSsl = true,
                    //    Host= "smtp.gmail.com",
                    //    Port = 587,
                    //    Credentials = new System.Net.NetworkCredential("rf.rosariofinanzas@gmail.com", "rosfin2011")
                    //};

                    var smtp = new System.Net.Mail.SmtpClient
                    {
                        Host = "localhost"
                    };

                    smtp.Send(correo);
                    
                    txtNombre.Enabled = false;
                    txtApellido.Enabled = false;
                    txtDNI.Enabled = false;
                    txtProvincia.Enabled = false;
                    txtEmail.Enabled = false;
                    btnEnviar.Enabled = false;

                    lblUsuarioInscripto.Text = "Su número de la suerte es el " + rd["nro"].ToString();
                    lblEmailConfirmacion.Visible = true;
                }
            }
            rd.Close();
            cn.Cerrar();  

        }
  

        private string LinkExtension(string Link)
        {
            return Link.Substring(Link.LastIndexOf(".") + 1);
        }
        

        private Stream Link(string link)
        {

            //This controls how many bytes to read at a time and send to the client
            int bytesToRead = 10000;

            // Buffer to read bytes in chunk size specified above
            byte[] buffer = new Byte[bytesToRead];

            WebClient wc = new WebClient();
            byte[] b = wc.DownloadData(link);

            Stream ms = new MemoryStream(b);

            return ms;
        }

        private string GetHtmlEmailSorteo(string nombreSorteo, string fecha, string nro)
        {

            string html = "";

            // CABECERA
            html += "<div style=\"padding: 30px; height: auto; background-color: rgb(243, 238, 225);\">";
            html += "<div style=\"text-align: center;\">";
            html += "</div>";
            html += "<div style=\"text-align: center; background-color: white;\">";
            html += "<div style=\"width: 100%; height: 20px; background-color: rgb(141, 105, 13);\">";
            html += "</div>";
            html += "<table style=\"width: 96%; height: 120px; text-align: left; margin-top: 10px; margin-right: 2%; margin-left: 2%; border-bottom-color: rgb(141, 105, 13); border-bottom-width: 3px; border-bottom-style: double; background-color: white;\">";
            html += "<tbody>";
            html += "<tr>";
            html += "<td>";
            html += " <img alt=\"Logo Rosario Finanzas\" border=\"0\" src=\"http://rosariofinanzas.com.ar/ckfinder/images/RosarioNews.jpg\" style=\"width: 174px; height: 44px;\" /></td>";
            html += "<td style=\"text-align: right;\">";
            html += "<span style=\"font-family: arial,helvetica,sans-serif; font-size: 24px;\"><strong>Sorteos</strong></span><br />";
            html += "<br />";
            html += "<span style=\"color: black; font-family: arial,helvetica,sans-serif; font-size: 14px;\"><a href=\"http://rosariofinanzas.com.ar\" style=\"text-decoration: none;\">www.rosariofinanzas.com.ar</a></span></td>";
            html += "</tr>";
            html += "</tbody>";
            html += "</table>";


            // CUERPO
            html += "<p>";
            html += "Usted está participando en el sorteo '<strong>" + nombreSorteo + "'</strong> que se realizará el día <strong>" + fecha + "</strong>";
            html += "</p>";


            html += "<p>";
            html += "Su número es: <strong>" + nro + "</strong>";
            html += "</p>";         


            // PIE
            html += "<p>";
            html += "Lea atentamente las <a href=\"http://rosariofinanzas.com.ar/Sorteo/BasesyCondiciones.aspx\" target=\"_blank\" style=\"text-decoration: none;\">Bases y Condiciones</a>";
            html += "</p>";
            html += "<p>";
            html += "<strong> Visite nuestra sección de cursos si desea aprender a manejar sus finanzas personales: </strong> <br/> http://rosariofinanzas.com.ar/cursos/cursos.html";
            html += "</p>";
            html += "<div style=\"padding: 10px; height: 25px; text-align: right; background-color: rgb(141, 105, 13);\">";
            html += "<a href=\"https://www.facebook.com/rosario.finanzas\" target=\"_blank\"><img alt=\"Facebook\" border=\"0\" src=\"http://rosariofinanzas.com.ar/ckfinder/images/face.png\" style=\"border-width: 0px; border-style: solid; width: 23px; height: 22px;\" /></a> <a href=\"https://twitter.com/rosariofinanzas\" target=\"_blank\"> <img alt=\"Twitter\" border=\"0\" src=\"http://rosariofinanzas.com.ar/ckfinder/images/twit.png\" style=\"border-width: 0px; border-style: solid; width: 23px; height: 22px;\" /></a></div>";
            html += "</div>";
            html += "</div>";
            html += "<p>";
            html += "</p>";

            return html;
        }

     
    }
}